<template>
  <div class="app-container">
    <!-- 搜索和新增区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="queryParams.kpiName" placeholder="请输入指标名称" clearable @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 指标表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog">新增指标</el-button>
      <el-table :data="kpiList" border style="width: 100%" class="indicator-table mt-2" v-loading="loading"
        :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column prop="kpiName" label="指标名称" width="180" />
        <el-table-column label="指标类型" width="120">
          <template #default="{ row }">
            {{ getDictLabel(kpiTypeOptions, row.kpiType) }}
          </template>
        </el-table-column>
        <el-table-column prop="dataSource" label="数据来源" width="150" />
        <el-table-column prop="calculationMethod" label="计算方式" />
        <el-table-column prop="unit" label="单位" width="100" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑指标对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="currentKpi" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="指标名称" prop="kpiName">
          <el-input v-model="currentKpi.kpiName" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="指标类型" prop="kpiType">
          <el-select v-model="currentKpi.kpiType" placeholder="请选择指标类型" style="width: 100%">
            <el-option v-for="item in kpiTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据来源" prop="dataSource">
          <el-input v-model="currentKpi.dataSource" placeholder="请输入数据来源" />
        </el-form-item>
        <el-form-item label="计算方式" prop="calculationMethod">
          <el-input v-model="currentKpi.calculationMethod" type="textarea" :rows="2" placeholder="请输入计算方式" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="currentKpi.unit" placeholder="请输入单位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  getKpiTypeList,
  getKpiConfigList,
  getKpiConfigDetail,
  addKpiConfig,
  updateKpiConfig,
  deleteKpiConfig
} from '@/api/prod_operate/sys_setting/kpi/detail'

// 加载状态
const loading = ref(false)

// 指标列表数据
const kpiList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  kpiName: ''
})

// 指标类型选项
const kpiTypeOptions = ref([])

// 当前操作的指标
const currentKpi = reactive({
  kpiConfigId: '',
  kpiName: '',
  dataSource: '',
  kpiType: '',
  calculationMethod: '',
  unit: ''
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增指标')
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  kpiName: [
    { required: true, message: '请输入指标名称', trigger: 'blur' }
  ],
  kpiType: [
    { required: true, message: '请选择指标类型', trigger: 'change' }
  ],
  dataSource: [
    { required: true, message: '请输入数据来源', trigger: 'blur' }
  ],
  calculationMethod: [
    { required: true, message: '请输入计算方式', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ]
})

// 根据字典值获取标签
const getDictLabel = (options, value) => {
  const item = options.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取指标类型列表
    const typeRes = await getKpiTypeList()
    kpiTypeOptions.value = typeRes.data

    // 获取指标列表
    await fetchKpiList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取指标列表
const fetchKpiList = async () => {
  try {
    loading.value = true
    const res = await getKpiConfigList(queryParams)
    kpiList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取指标列表失败:', error)
    ElMessage.error('获取指标列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchKpiList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchKpiList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchKpiList()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增指标'
  resetCurrentKpi()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getKpiConfigDetail(row.kpiConfigId)
    Object.assign(currentKpi, res.data)
    dialogTitle.value = '编辑指标'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取指标详情失败:', error)
    ElMessage.error('获取指标详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前指标
const resetCurrentKpi = () => {
  currentKpi.kpiConfigId = ''
  currentKpi.kpiName = ''
  currentKpi.dataSource = ''
  currentKpi.kpiType = ''
  currentKpi.calculationMethod = ''
  currentKpi.unit = ''
}

// 确认保存
const confirmSave = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增指标') {
      await addKpiConfig(currentKpi)
      ElMessage.success('新增指标成功')
    } else {
      await updateKpiConfig(currentKpi)
      ElMessage.success('修改指标成功')
    }

    dialogVisible.value = false
    fetchKpiList()
  } catch (error) {
    console.error('保存指标失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该指标吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteKpiConfig(row.kpiConfigId)
      ElMessage.success('删除成功')
      fetchKpiList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.mt-2 {
  margin-top: 20px;
}

.indicator-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容居中对齐 */
:deep(.el-table th),
:deep(.el-table td) {
  text-align: center !important;
}

/* 表格单元格内边距 */
:deep(.el-table .cell) {
  padding: 8px;
}
</style>